package com.manage.common.core.utils;
 
import java.util.*;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.manage.common.core.base.LocalDateConverter;
import com.manage.common.core.exception.BaseException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhangqing
 * @date 2021/11/23
 */
@Component
@SuppressWarnings("ALL")
public class EasyExcelUtil {
 
    /**
     * @description web导出
     *
     * @params [response, list, fileNames, sheetName]
     * @return void
     * @author xiaoyinchuan
     * @date 2020/11/27 0027 11:42
     **/
    public void downloadFailedUsingJson(HttpServletResponse response, List<?> list, String fileNames, String sheetName) throws IOException {
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException();
        }
        if (StringUtils.isEmpty(fileNames)) {
            fileNames = new Date().toString();
        }
        if (StringUtils.isEmpty(sheetName)) {
            sheetName = "Sheet1";
        }
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(fileNames, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), list.get(0).getClass()).autoCloseStream(Boolean.FALSE).sheet(sheetName)
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONUtil.toJsonStr(map));
        }
    }

    /**
     * 导出到本地
     * @param list 需要导出的数据
     * @param path 导出路径
     * @param fileNames 文件名称
     * @param sheetName sheet名称
     */
    public void downloadLocal(List<?> list, String path, String fileNames, String sheetName, Set<String> includeColumnFiledNames) {
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException();
        }
        if (StringUtils.isEmpty(fileNames)) {
            fileNames = new Date().toString();
        }
        if (StringUtils.isEmpty(sheetName)) {
            sheetName = "Sheet1";
        }
        ExcelWriter excelWriter = EasyExcel.write(path + fileNames + ".xlsx", list.get(0).getClass())
                .registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter())
                .includeColumnFiledNames(includeColumnFiledNames)
                .build();
        try {
            //标题
            WriteSheet test = EasyExcel.writerSheet(sheetName).build();
            //写入
            excelWriter.write(list, test);
        } catch (Exception e) {
            throw new BaseException(e);
        } finally {
            // 关闭
            excelWriter.finish();
        }
    }
}